/**
 * 
 */
package com.nexttwist.util;

import java.io.IOException;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

/**
 * @author HarishKumarG
 *
 */
public class MyMediaPlayer {
	
	private MediaPlayer mMediaPlayer = new MediaPlayer();
	private static MyMediaPlayer mMyMediaPlayer;
	
	public MyMediaPlayer() {
		mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				try {
					pause();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public static MyMediaPlayer getInstance() {
		if (null == mMyMediaPlayer) {
			mMyMediaPlayer = new MyMediaPlayer();
		}
		return mMyMediaPlayer;
	}
	
	/**
	 * Start playing track, resets if any track is playing already
	 * @param path
	 */
	public void play(String path) {
		try {
			if (mMediaPlayer.isPlaying()) {
				mMediaPlayer.stop();
				mMediaPlayer.reset();
			}
			mMediaPlayer.setDataSource(path);
			mMediaPlayer.prepare();
			mMediaPlayer.start();
		} catch (IllegalArgumentException | SecurityException
				| IllegalStateException | IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Stop playing track
	 */
	public void pause() {
		if (mMediaPlayer.isPlaying()) {
			mMediaPlayer.stop();
		}
		mMediaPlayer.reset();
		mMediaPlayer.release();
		mMyMediaPlayer = null;
	}

}
